package wiki.mdzz.learn_android.controllers

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import wiki.mdzz.learn_android.R
import wiki.mdzz.learn_android.data.Fruit
import wiki.mdzz.learn_android.data.FruitRecyclerAdapter
import wiki.mdzz.learn_android.databinding.ActivitySndBinding
import wiki.mdzz.learn_android.utils.BaseActivity

class SndActivity : BaseActivity() {
    private lateinit var binding: ActivitySndBinding
    private val fruitList = ArrayList<Fruit>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivitySndBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val extraData = intent.getStringExtra("extra_data")
        Log.d("FstActivity", "extra data is $extraData")

        binding.call.setOnClickListener {
            val intent = Intent(Intent.ACTION_DIAL)
            intent.data = Uri.parse("tel:10086")
            startActivity(intent)
        }

        binding.btn4.setOnClickListener {
            val intent = Intent()
            intent.putExtra("data_response", "Hello MainActivity")
            setResult(RESULT_OK, intent)
            finish()
        }
        initFruits()
        binding.recyclerView.layoutManager =
            StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL)
        binding.recyclerView.adapter = FruitRecyclerAdapter(fruitList)
    }

    private fun initFruits() {
        repeat(2) {
            fruitList.add(Fruit(getRandomLengthStr("Apple"), R.drawable.test))
            fruitList.add(Fruit(getRandomLengthStr("Banana"), R.drawable.test))
            fruitList.add(Fruit(getRandomLengthStr("Orange"), R.drawable.test))
            fruitList.add(Fruit(getRandomLengthStr("Pear"), R.drawable.test))
            fruitList.add(Fruit(getRandomLengthStr("Grape"), R.drawable.test))
            fruitList.add(Fruit(getRandomLengthStr("Pineapple"), R.drawable.test))
            fruitList.add(Fruit(getRandomLengthStr("Strawberry"), R.drawable.test))
            fruitList.add(Fruit(getRandomLengthStr("Cherry"), R.drawable.test))
            fruitList.add(Fruit(getRandomLengthStr("Mango"), R.drawable.test))
        }
    }

    private fun getRandomLengthStr(str: String): String {
        val n = (1..20).random()
        val builder = StringBuilder()
        repeat(n) {
            builder.append(str)
        }
        return builder.toString()
    }
}